package com.freecycle.sg.ui;

import java.util.HashMap;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.freecycle.sg.R;
import com.freecycle.sg.sqlite.Freebie.Freebies;
import com.freecycle.sg.sqlite.Freebie.ReferenceData;
import com.freecycle.sg.ui.widget.BezelImageView;
import com.freecycle.sg.utils.BitmapUtils;
import com.freecycle.sg.utils.BitmapUtils.OnFetchCompleteListener;
import com.freecycle.sg.utils.Config;
import com.freecycle.sg.utils.NotifyingAsyncQueryHandler;
import com.freecycle.sg.utils.NotifyingAsyncQueryHandler.AsyncQueryListener;

public class FreebieDetailFragment extends Fragment implements AsyncQueryListener {

	private static final String TAG = "FreebieDetailFragment";
	
	private NotifyingAsyncQueryHandler mHandler;
	
	private HashMap<String, String> mCategories;
	
	private String freebieId;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mHandler = new NotifyingAsyncQueryHandler(getActivity()
				.getContentResolver(), this);
		setHasOptionsMenu(true);
		
		reloadFromArguments(getArguments());
	}
	
	public void reloadFromArguments(Bundle arguments) {
		// Abort currently running query if any
		mHandler.cancelOperation(FreebiesQuery._TOKEN);
		mHandler.cancelOperation(ReferenceQuery._TOKEN);
		
		// Load reference for categories
		mHandler.startQuery(ReferenceQuery._TOKEN, null,
				ReferenceData.CONTENT_URI, 
				ReferenceQuery.projection,
				ReferenceData.REF_DATA_TYPE + "=?", 
				new String[] { Config.REF_CATEGORIES },
				ReferenceData.DEFAULT_SORT);

		// Build intent based on loaded arguments
		final Intent intent = BaseActivity.fragmentArgumentsToIntent(arguments);
		final Uri freebieUri = intent.getData();
		freebieId = Freebies.getFreebieId(freebieUri); 

		if (freebieUri == null) {
			return;
		}

		// Load freebie from local database
		mHandler.startQuery(FreebiesQuery._TOKEN, null,
				Freebies.CONTENT_URI, 
				FreebiesQuery.projection,
				Freebies.FREEBIE_ID + "=?",
				new String[] { freebieId },
				Freebies.DEFAULT_SORT);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.freebie_detail, container, false);
	}
	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.back_menu_items, menu);
		inflater.inflate(R.menu.edit_menu_items, menu);
		super.onCreateOptionsMenu(menu, inflater);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.menu_back) {
			getActivity().onBackPressed();
			return true;
		} else if (item.getItemId() == R.id.menu_edit) {
			final Uri freebieUri = Freebies.buildFreebieUri(freebieId);
			final Intent intent = new Intent(Intent.ACTION_EDIT, freebieUri);
			startActivity(intent);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onQueryComplete(int token, Object cookie, Cursor c) {
		getActivity().startManagingCursor(c);
		
		if (token == ReferenceQuery._TOKEN) {
			mCategories = new HashMap<String, String>();
			
			if (c.moveToFirst()) {
				do {
					String key = c.getString(ReferenceQuery.ABBREVIATION);
					String value = c.getString(ReferenceQuery.NAME);
					mCategories.put(key, value);
				} while (c.moveToNext());
			}
		} else if (token == FreebiesQuery._TOKEN) {
			initData(c);
		}
	}
	
	private void initData(Cursor c) {
		if (!c.moveToFirst()) {
			return;
		}
		
		final TextView title = (TextView) getActivity().findViewById(R.id.title);
		final TextView category = (TextView) getActivity().findViewById(R.id.category);
		final TextView date = (TextView) getActivity().findViewById(R.id.date_added);
		final TextView location = (TextView) getActivity().findViewById(R.id.location);
		final TextView name = (TextView) getActivity().findViewById(R.id.name);
		final TextView description = (TextView) getActivity().findViewById(R.id.description);
		final BezelImageView image= (BezelImageView) getActivity().findViewById(R.id.image);
		
		title.setText(c.getString(FreebiesQuery.TITLE));
		
		String cat = c.getString(FreebiesQuery.CATEGORY);
		if (!TextUtils.isEmpty(cat)) {
			if (mCategories != null) {
				category.setText(mCategories.get(cat));
			}
		}
		
		String added = c.getString(FreebiesQuery.ADDED);
		if (!TextUtils.isEmpty(added)) {
			try {
				long millis = Long.valueOf(added);
				date.setText(DateUtils.formatDateTime(getActivity(), millis,
						DateUtils.FORMAT_ABBREV_ALL));
			} catch (NumberFormatException e) {
				Log.e(TAG, e.toString());
			}
		}
		
		location.setText(c.getString(FreebiesQuery.FORMATTED_ADDRESS));
		name.setText(c.getString(FreebiesQuery.NAME));
		description.setText(c.getString(FreebiesQuery.DESCRIPTION));
		
		// Fetch the image 
		try {
			Integer id = new Integer(c.getString(FreebiesQuery.FREEBIE_ID));
			if (id != null) {
				if (id.intValue() != -1) {
					BitmapUtils.fetchImage(getActivity(), "http://media.rioswimwearshop.com" +
							"/media/catalog/product/B/i/Bikini-Bottom-Calcinha-" +
							"Istambul-1.jpg&w=1366&h=1024&ei=wgFAT4yWLJGnrAfjiIW0Bw&zoom=1",
						new OnFetchCompleteListener() {
							@Override
							public void onFetchComplete(Object cookie, Bitmap result) {
								if (result != null) {
									image.setImageBitmap(result);
								}
							}
						});
				}
			}	
		} catch (NumberFormatException e) {
			Log.e(TAG, e.toString());
		}
		
	}
	
	private interface FreebiesQuery {
		int _TOKEN = 0x231;

		String[] projection = { Freebies._ID, 
				Freebies.FREEBIE_ID,
				Freebies.ADDED, 
				Freebies.LATITUDE,
				Freebies.LONGITUDE, 
				Freebies.FORMATTED_ADDRESS, 
				Freebies.TITLE, 
				Freebies.DESCRIPTION,
				Freebies.CATEGORY,
				Freebies.PHONE,
				Freebies.NAME,
				};
		
		int FREEBIE_ID = 1;
		int ADDED = 2;
		int LATITUDE = 3;
		int LONGITUDE = 4;
		int FORMATTED_ADDRESS = 5;
		int TITLE = 6;
		int DESCRIPTION = 7;
		int CATEGORY = 8;
		int PHONE = 9;
		int NAME = 10;
	}
	
	private interface ReferenceQuery {
		int _TOKEN = 0x232;

		String[] projection = { 
				ReferenceData._ID,
				ReferenceData.REF_DATA_TYPE,
				ReferenceData.ABBREVIATION,
				ReferenceData.NAME,
				ReferenceData.MARKER_URL,
				};
		
		int REF_DATA_TYPE = 1;
		int ABBREVIATION = 2;
		int NAME = 3;
		int MARKER_URL = 4;
	}
	
}
